package com.learn.qy.cp.api.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.learn.qy.cp.bean.WxAccessToken;
import com.learn.qy.cp.config.WxCpConfigStorage;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : Yu.Tan
 * @date : 2023/6/25 14:44
 * @desc : **
 */
@Slf4j
public class WxCpServiceImpl extends BaseWxCpServiceImpl {

    protected WxCpConfigStorage wxCpConfigStorage;

    public void setWxCpConfigStorage(WxCpConfigStorage wxCpConfigStorage) {
        this.wxCpConfigStorage = wxCpConfigStorage;
    }

    @Override
    public String getAccessToken(boolean forceRefresh) throws Exception {

        String apiUrl = this.wxCpConfigStorage.getApiUrl("/cgi-bin/gettoken?corpid=%s&corpsecret=%s");
        String url = String.format(apiUrl, this.wxCpConfigStorage.getCorpId(), this.wxCpConfigStorage.getAgentSecret());
        HttpResponse response = HttpUtil.createGet(url).execute();
        if (response.isOk()) {
            String body = response.body();
            WxAccessToken accessToken = JSONUtil.toBean(body, WxAccessToken.class);
            log.info("body={}", JSONUtil.toJsonStr(body));
            return accessToken.getAccessToken();
        }
        log.info("{}", JSONUtil.toJsonStr(response));
        return JSONUtil.toJsonStr(response);
    }
}
